<?php

namespace app\index\service;

use app\index\model\Member as MemberModel;
use think\cache\driver\Redis as RedisModel;

class Member
{

    /**
     *  获取用户信息
     * @param type $user_id
     * @return type
     */
    public static function getInfoByID($user_id)
    {

        $key = "member_{$user_id}_info";
        $redis_model = self::getRedisInsrance();
        $member_info = $redis_model->get($key);
        if (empty($member_info))
        {
            $member_info = MemberModel::where('id', $user_id)
                    ->find()
                    ->toArray();
            $redis_model->set($key, $member_info);
        }
        return $member_info;
    }

    /**
     * 设置用户信息
     * @param type $info
     * @return $info
     */
    public static function setInfo($info)
    {
        $user_id = $info['id'];
        $key = "member_{$user_id}_info";
        $redis_model = self::getRedisInsrance();
        $redis_model->set($key, $info);
        return $info;
    }

    /**
     * 返回redis实例
     * @return \think\cache\driver\Redis
     */
    private static function getRedisInsrance()
    {
        return $redis_model = new RedisModel([
            'expire' => 60 * 60 * 24,
        ]);
    }

    public static function change_info($member_id)
    {
        $MemberModel = MemberModel::find($member_id);
        $MemberModel->username = input('username', '');
        $affect_row = $MemberModel->save();
        if ($affect_row)
        {
           self::setInfo($MemberModel->toArray());
        }
        return json([ 'code' => 1, 'affect_row' => $affect_row ]);
    }

    public static function change_password($member_id)
    {
        $data = input('post.');
        $validate_rule = [
            'password' => 'require|min:6',
        ];
        $validate_msg = [
            'password.min' => '新密码最少六位',
            'password.require' => '新密码必填',
        ];
        $validate = validate();
        $validate->message($validate_msg);
        $validate_res = $validate->check($data, $validate_rule) ? TRUE : $validate->getError();
        $MemberModel = MemberModel::find($member_id);
        $new_password = input('password', '');
        $old_password = input('old_password', '');
        if ($validate_res !== TRUE)
        {
            return json([ 'code' => '0', 'msg' => is_array($validate_res) ? implode(',', $validate_res) : $validate_res ]);
        }
        if (password_verify($old_password, $MemberModel->password) == false)
        {
            return json([ 'code' => '0', 'msg' => '原密码错误' ]);
        }
        $MemberModel->password = encrypt_password($new_password);
        $affect_row = $MemberModel->save();
        if ($affect_row)
        {
            self::setInfo($MemberModel->toArray());
        }
        return json([ 'code' => 1, 'affect_row' => $affect_row ]);
    }

}
